import { Base } from '../../utils/base.js';
import { Product } from "../product/product-model.js"
var product = new Product();
/*
* 购物车数据存放在本地，
* 当用户选中某些商品下单购买时，会从缓存中删除该数据，更新缓存
* 当用用户全部购买时，直接删除整个缓存
*
*/
class Cart extends Base {
  constructor() {
    super();
  };

  //加载购物车数据
 getCartData(callback) {
    var param = {
      url: 'cart/index',
      type: 'post',
      data:{},
      sCallback: function (data) {
        callback && callback(data);
      }
    };
    this.request(param);
  }

  //勾选后更新总价
  getcalculatorTototal(selectedIds,callback){
   var param = {
     url: 'cart/calculator',
     type: 'post',
     data: { cart_ids: selectedIds},
     sCallback: function (data) {
       callback && callback(data);
     }
   };
   this.request(param);
 }



 getCartTotalCounts(flag,data) {
     var counts1 = 0,
         counts2 = 0,
         selectedShopCounts=0,
         shopchild = 0,
         selectedShop = false;

   for (let i = 0; i < data.length; i++) {
     var childLen = data[i].length;
     for(let j = 0;j<childLen;j++){
       data[i][j].num = parseInt(data[i][j].num);
       if (flag) {
         if (data[i][j].selected == 1) {
           counts1 += data[i].num;
           counts2++;
         }
       } else {
         counts1 += data[i].num;
         counts2++;
       }
     }
   }
  
   return {
     counts1: counts1,
     counts2: counts2,
   };
 };

 //数量调整后更新总价
 getChangeCounts(id,num,callback){
  var param = {
    url: 'cart/change',
    type: 'post',
    data: { 'id':id,'num':num },
    sCallback: function (data) {
      callback && callback(data);
    }
  };
  this.request(param);
}

//往购物车添加数据
  addProduct2Cart(params,callback) {
  var param = {
    url: 'cart/add',
    data: params,
    type: 'post',
    sCallback: function (data) {
      var cart = wx.getStorageSync('cart');
      cart = cart ? cart : 0;
      cart++;
      wx.setStorageSync('cart', cart);
      wx.setTabBarBadge({
        index: 2,   //代表哪个tabbar（从0开始）
        text: cart + ''		//显示的内容
      })
      callback && callback(data);
    }
  };
  this.request(param);
}



  /*
  * 删除某些商品
  */
  delete(id,callback) {
    var param = {
      url: 'cart/delete',
      data: { 'id': id},
      type: 'post',
      sCallback: function (data) {
        callback && callback(data);
      }
    };
    this.request(param);
  }
  
}

export { Cart };